<?php

namespace app\common\service\merchant;
use app\common\cache\merchant\MerchantCache;
use app\common\cache\merchant\MerchantUserCache;
use app\common\model\Merchant\MerchantBillModel;
use app\common\model\Merchant\MerchantMenuModel;
use app\common\model\Merchant\MerchantModel;
use app\common\model\product\ShopProductTypeModel;
use think\facade\Db;
/**
 * 商家
 */
class MerchantService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
        'id/d'=>null,
        'merchant_pid/d'=>null,
        'title/s'=>null,
        'real_name/s'=>null,
        'is_disable/d'=>0,
        'is_delete/d'=>0,
        'mer_phone/s'=>null,
        'mer_account/s'=>null,
        'mer_pwd/s'=>null,
        'mer_qq/s'=>null,
        'mer_weixin/s'=>null,
        'mer_address/s'=>null,
        'promotion_user_id/d'=>null,
        'is_invite/d'=>0,
        'is_withdrawal/d'=>0,
        'mer_money/f'=>0,
        'mer_commission/f'=>0,
        'mer_withdrawal/f'=>0,
        'mer_gifts/f'=>0,
        'sort/d'=>250,
        'remark/s'=>null,
        'shop_product_type_ids/a'=>[]
    ];
    /**
     * 商家列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MerchantModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,merchant_pid,title,real_name,is_disable,is_delete,create_uid,update_uid,create_time,update_time,mer_phone,mer_account,mer_pwd,mer_qq,mer_weixin,mer_address,promotion_user_id,is_invite,is_withdrawal,mer_money,mer_commission,mer_withdrawal,mer_gifts,sort,remark,shop_product_type_ids';
        }
        if (empty($order)) {
            $order = ['sort'=>'asc',$pk => 'desc'];
        }
        $with     = ['groups','promotion' => function ($query) {
            $query->field('promotion_user_id,nickname,username');
        },'parentMer' => function ($query) {
            $query->field('id,merchant_pid,title,real_name,mer_phone');
        }];
        $append   = ['group_names','group_ids'];
        $hidden   = ['groups','group_ids'];
        if ($page == 0 || $limit == 0) {
            return $model->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->field($field)->with($with)->append($append)->hidden($hidden)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        foreach ($list as $key=>$val){
            $list[$key]['shop_product_type_titles'] ="";
            //获取活动分类
            if($val['shop_product_type_ids']){
                $type_ids= explode(',',$val['shop_product_type_ids']);
                $product_types = ShopProductTypeModel::where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('id','in',$list[$key]['shop_product_type_ids'])
                    ->field('id,title')
                    ->select()
                    ->toArray();
                $list[$key]['shop_product_type_ids'] =array_column($product_types,'id');
                $list[$key]['shop_product_type_titles'] =array_column($product_types,'title');
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }

    /**
     * 资金明细
     * @param $where
     * @param $page
     * @param $limit
     * @param $order
     * @param $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function bill($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MerchantBillModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,money,principal,commission,principal_balance,commission_balance,type,merchant_shop_id,data_id,title,remark,create_time';
        }
        if (empty($order)) {
            $order = ['create_time'=>'desc',$pk => 'desc'];
        }
        if ($page == 0 || $limit == 0) {
            return $model->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        foreach ($list as $key=>$val) {
            $list[$key]['type_str'] = MerchantBillModel::getType($val['type'],2);
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }

    /**
     * 资金明细类型
     * @return array[]
     */
    public static function getBillType(){
        return MerchantBillModel::TYPE;
    }
    /**
     * 商家信息
     *
     * @param int  $id   商家id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = MerchantCache::get($id);
        if (empty($info)) {
            $with     = ['promotion' => function ($query) {
                $query->field('promotion_user_id,nickname,username');
            },'parentMer' => function ($query) {
                $query->field('id,merchant_pid,title,real_name,mer_phone');
            }];
            $model = new MerchantModel();
            $info = $model->with($with)->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('商家不存在：' . $id);
                }
                return [];
            }
            $info = $info->toArray();

            if($info['shop_product_type_ids']){
                $product_type_ids = explode(',',$info['shop_product_type_ids']);
                foreach ($product_type_ids as &$val) {
                    $val = (int) $val;
                }
                $info['shop_product_type_ids'] =$product_type_ids;
            }else{
                $info['shop_product_type_ids'] =[];
            }
            MerchantCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 商家添加
     *
     * @param array $param 商家信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new MerchantModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();
        // 启动事务
        $model->startTrans();
        try {
            //绑定活动分类
            if(isset($param['shop_product_type_ids']) && $param['shop_product_type_ids']){
                $param['shop_product_type_ids'] = implode(',',$param['shop_product_type_ids']);
            }else{
                $default_product_types = ShopProductTypeModel::
                    where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('is_default',1)
                    ->field('id')
                    ->select()
                    ->toArray();
                if($default_product_types){
                    $param['shop_product_type_ids'] =implode(',',array_column($default_product_types,'id'));
                }
            }
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            $param[$pk] = $id;
            /******************创建角色******************************/
            $menu_list = Db::name('merchant_menu')->where('is_delete','<>',1)->field('menu_id')->select()->toArray();
            $role_data = array(
                'mer_id'=>$id,//商家ID
                'role_name'=>'超级管理员',//角色名称
                'role_desc'=>'超级管理员',//角色描述
                'remark'=>'系统默认',//备注
                'sort'=>1,//排序
                'is_admin'=>1,//是否为系统角色：1、不允许操作 0、否
                'menu_ids'=>array_column($menu_list,'menu_id')
            );
            $role = MerchantRoleService::add($role_data);
            /******************创建用户******************************/
            $user_data = array(
                'mer_id'=>$id,//商家id
                'number'=>'001',//编号
                'nickname'=>isset($param['real_name'])?$param['real_name']:$param['mer_account'],//用户昵称
                'username'=>$param['mer_account'],//用户账号
                'password'=>$param['mer_pwd'],//密码
                'phone'=>$param['mer_phone'],//手机
                'remark'=>'系统默认',//备注
                'sort'=>1,//排序
                'is_super'=>1,//是否超管，1是0否
                'is_admin'=>1,//是否为系统角色：1、不允许操作 0、否
                'role_ids'=>[$role['role_id']]
            );
            $role = MerchantUserService::add($user_data);
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        return $param;
    }
     /**
     * 商家修改
     *
     * @param int|array $ids   商家id
     * @param array     $param 商家信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new MerchantModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        if($param['shop_product_type_ids']){
            $param['shop_product_type_ids'] = implode(',',$param['shop_product_type_ids']);
        }
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        MerchantCache::del($ids);
        return $param;
    }
    /**
     * 商家删除
     *
     * @param array $ids  商家id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new MerchantModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        MerchantCache::del($ids);
        return $update;
    }


    /**
     * 商家支出
     * @Author: 易军辉
     * @DateTime:2024-06-06 18:42
     * @param $money 消费金额
     * @param $principal 消费本金
     * @param $commission 消费佣金
     * @param $title 消费名称
     * @param $data_id 关联表ID
     * @param $merchant_shop_id 店铺ID
     * @param $remark 备注
     * @param $mer_id 商家id
     * @param $exce 异常是否报错
     */
    public static function consumption($money=0,$principal=0,$commission=0,$title="",$data_id=null,$merchant_shop_id=null,$remark=null,$mer_id=null,$exce = true)
    {
        //商家ID
        if(!$mer_id){
            $mer_id = mer_id(true);
        }
        //创建用户ID
        $create_uid = mer_user_id();
        if($create_uid<=0){
            $create_uid = user_id();
        }
        $model = new MerchantBillModel();
        $pk = $model->getPk();
        // 启动事务
        $model->startTrans();
        try {
            $merModel = new MerchantModel();
            $mer_money = $merModel->where('id',$mer_id)->field('id,mer_money,mer_commission')->find();
            if($mer_money['mer_money']<$principal && $exce){
                exception("您的本金".$mer_money['mer_money']."不足，请充值");
            }
            if($mer_money['mer_commission']<$commission){
                //判断佣金不足能否从本金扣
                $price_difference = abs(bcsub($mer_money['mer_commission'], $commission,2));
                if($mer_money['mer_money']>$price_difference || !$exce){
                $transfer_res = self::transferAccounts($mer_id,$price_difference,$mer_money,$merchant_shop_id,$data_id,$remark,$exce);
                if($transfer_res){
                    $mer_money['mer_commission'] = bcadd($mer_money['mer_commission'],$price_difference,2);
                    $mer_money['mer_money']= bcsub($mer_money['mer_money'],$price_difference,2);
                }
                }else if($exce){
                    exception("您的本金".$mer_money['mer_money']."不足，请充值");
                }
            }
            if(bccomp($money, bcadd($principal, $commission,2)) !=0 && $exce){
                exception("金额有误，支付失败，请稍后再试！");
            }
            $param = array(
                'create_uid'=>$create_uid,
                'create_time'=>datetime(),
                'mer_id'=>$mer_id,
                'money'=>-$money,//操作金额
                'principal'=>-$principal,//本金
                'commission'=>-$commission,//佣金
                'principal_balance'=>bcsub($mer_money['mer_money'],$principal,2),//本金余额
                'commission_balance'=>bcsub($mer_money['mer_commission'],$commission,2),//佣金余额
                'type'=>MerchantBillModel::getType('CONSUMPTION',1),
                'merchant_shop_id'=>$merchant_shop_id,
                'data_id'=>$data_id,
                'title'=>$title,
                'remark'=>$remark,
            );
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            $param[$pk] = $id;
            $res = $merModel->where('id',$mer_id)->update(['mer_money'=>bcsub($mer_money['mer_money'],$principal,2),'mer_commission'=>bcsub($mer_money['mer_commission'],$commission,2)]);
            if (empty($res) && $exce) {
                exception('支付失败');
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        return $param;
    }

    /**
     * 余额转佣金
     * @Author: 易军辉
     * @DateTime:2024-10-12 10:04
     * @param $mer_id 商家id
     * @param $money 转账金额
     * @param $mer_money  商家余额信息
     * @param $merchant_shop_id 商家店铺
     * @param $data_id 关联id
     * @param $remark 备注
     * @param $exce 报错是否提示
     * @return array
     * @throws \think\Exception
     */
    private static function transferAccounts($mer_id,$money,$mer_money,$merchant_shop_id,$data_id,$remark,$exce)
    {
        $model = new MerchantBillModel();
        $pk = $model->getPk();
        $param = array(
            'create_uid'=>operate_user_id(),
            'create_time'=>datetime(),
            'mer_id'=>$mer_id,
            'money'=>$money,//操作金额
            'principal'=>-$money,//本金
            'commission'=>$money,//佣金
            'principal_balance'=>bcsub($mer_money['mer_money'],$money,2),//本金余额
            'commission_balance'=>bcadd($mer_money['mer_commission'],$money,2),//佣金余额
            'type'=>MerchantBillModel::getType('RECHARGE',1),
            'merchant_shop_id'=>$merchant_shop_id,
            'data_id'=>$data_id,
            'title'=>"余额转佣金",
            'remark'=>$remark,
        );
        // 启动事务
        $model->startTrans();
        try {
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            $param[$pk] = $id;

            $res = Db::name('merchant')->where('id',$mer_id)->update(['mer_money'=>bcsub($mer_money['mer_money'],$money,2),'mer_commission'=>bcadd($mer_money['mer_commission'],$money,2)]);
            if (empty($res) && $exce) {
                exception('余额转佣金失败');
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        return $param;
    }

    /**
     * 退款给商家
     * @Author: 易军辉
     * @DateTime:2024-06-14 15:42
     * @param $mer_id 商家ID
     * @param $money 收入金额
     * @param $principal 消费本金
     * @param $commission 消费佣金
     * @param $title 收入名称
     * @param $data_id 关联表ID
     * @param $merchant_shop_id 店铺ID
     * @param $remark 备注
     */
    public static function refund($mer_id=null,$money=0,$principal=0,$commission=0,$title="",$data_id=null,$merchant_shop_id=null,$remark=null)
    {
        if(bccomp($money, bcadd($principal, $commission,2)) !=0){
            exception("金额有误，支付失败，请稍后再试！");
        }
        //商家ID
        if(!$mer_id){
            $mer_id = mer_id(true);
        }
        //创建用户ID
        $create_uid = mer_user_id();
        if($create_uid<=0){
            $create_uid = user_id();
        }
        $merModel = new MerchantModel();
        $mer_money = $merModel->where('id',$mer_id)->field('id,mer_money,mer_commission')->find();

        $model = new MerchantBillModel();
        $pk = $model->getPk();
        $param = array(
            'create_uid'=>$create_uid,
            'create_time'=>datetime(),
            'mer_id'=>$mer_id,
            'money'=>$money,
            'principal'=>$principal,//本金
            'commission'=>$commission,//佣金
            'principal_balance'=>bcadd($mer_money['mer_money'],$principal,2),//本金余额
            'commission_balance'=>bcadd($mer_money['mer_commission'],$commission,2),//佣金余额
            'type'=>MerchantBillModel::getType('REFUND',1),
            'merchant_shop_id'=>$merchant_shop_id,
            'data_id'=>$data_id,
            'title'=>$title,
            'remark'=>$remark,
        );
        // 启动事务
        $model->startTrans();
        try {
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            $param[$pk] = $id;
            $res = $merModel->where('id',$mer_id)->update([
                'mer_money'=>bcadd($mer_money['mer_money'],$principal,2),
                'mer_commission'=>bcadd($mer_money['mer_commission'],$commission,2)]);
            if (empty($res)) {
                exception('退款失败');
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        return $param;
    }

    /**
     * 指定买手分组
     * @Author: 易军辉
     * @DateTime:2024-06-27 09:51
     * @param $ids
     * @param $param
     */
    public static function member_group($ids,$param = [])
    {
        $model = new MerchantModel();
        $pk = $model->getPk();
        $list = $model->where($pk, 'in', $ids)->select();
        foreach ($list as $key=>$info){
            $info = $info->append(['group_ids']);
            relation_update($info, $info['group_ids'], $param['group_ids'], 'groups');
        }
        return $param;
    }

    /**
     * 商家充值
     * @Author: 易军辉
     * @DateTime:2024-06-14 15:42
     * @param $mer_id 商家ID
     * @param $money 充值金额
     * @param $principal 充值本金
     * @param $commission 充值佣金
     * @param $title 收入名称
     * @param $data_id 关联表ID
     * @param $remark 备注
     */
    public static function recharge($mer_id=null,$money=0,$principal=0,$commission=0,$title="",$data_id=null,$remark=null)
    {
        if(bccomp($money, bcadd($principal, $commission,2)) !=0){
            exception("金额有误，充值失败，请稍后再试！");
        }
        //商家ID
        if(!$mer_id){
            $mer_id = mer_id(true);
        }
        //创建用户ID
        $create_uid = mer_user_id();
        if($create_uid<=0){
            $create_uid = user_id();
        }
        $merModel = new MerchantModel();
        $mer_money = $merModel->where('id',$mer_id)->field('id,mer_money,mer_commission')->find();

        $model = new MerchantBillModel();
        $pk = $model->getPk();
        $param = array(
            'create_uid'=>$create_uid,
            'create_time'=>datetime(),
            'mer_id'=>$mer_id,
            'money'=>$money,
            'principal'=>$principal,//本金
            'commission'=>$commission,//佣金
            'principal_balance'=>bcadd($mer_money['mer_money'],$principal,2),//本金余额
            'commission_balance'=>bcadd($mer_money['mer_commission'],$commission,2),//佣金余额
            'type'=>MerchantBillModel::getType('RECHARGE',1),
            'data_id'=>$data_id,
            'title'=>$title,
            'remark'=>$remark,
        );
        // 启动事务
        $model->startTrans();
        try {
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            $param[$pk] = $id;
            $res = $merModel->where('id',$mer_id)->update([
                'mer_money'=>bcadd($mer_money['mer_money'],$principal,2),
                'mer_commission'=>bcadd($mer_money['mer_commission'],$commission,2)]);
            if (empty($res)) {
                exception('充值失败');
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        return $param;
    }


    /**
     * 商家提现
     * @Author: 易军辉
     * @DateTime:2024-06-06 18:42
     * @param $money 提现金额
     * @param $principal 提现本金
     * @param $commission 提现佣金
     * @param $title 提现名称
     * @param $data_id 关联表ID
     * @param $remark 备注
     */
    public static function withdrawal($money=0,$principal=0,$commission=0,$title="",$data_id=null,$remark=null)
    {
        $merModel = new MerchantModel();
        $mer_money = $merModel->where('id',mer_id())->field('id,mer_money,mer_commission')->find();
        if($mer_money['mer_money']<$principal){
            exception("您的本金".$mer_money['mer_money']."不足，无法提现");
        }
        if($mer_money['mer_commission']<$commission){
            exception("您的佣金".$mer_money['mer_commission']."不足，无法提现");
        }
        if(bccomp($money, bcadd($principal, $commission,2)) !=0){
            exception("金额有误，提现失败，请稍后再试！");
        }
        $model = new MerchantBillModel();
        $pk = $model->getPk();
        $param = array(
            'create_uid'=>mer_user_id(true),
            'create_time'=>datetime(),
            'mer_id'=>mer_id(true),
            'money'=>-$money,//操作金额
            'principal'=>-$principal,//本金
            'commission'=>-$commission,//佣金
            'principal_balance'=>bcsub($mer_money['mer_money'],$principal,2),//本金余额
            'commission_balance'=>bcsub($mer_money['mer_commission'],$commission,2),//佣金余额
            'type'=>MerchantBillModel::getType('WITHDRAWAL',1),
            'data_id'=>$data_id,
            'title'=>$title,
            'remark'=>$remark,
        );
        // 启动事务
        $model->startTrans();
        try {
            $model->save($param);
            $id = $model->$pk;
            if (empty($id)) {
                exception();
            }
            $param[$pk] = $id;
            $res = $merModel->where('id',mer_id())->update(['mer_money'=>bcsub($mer_money['mer_money'],$principal,2),'mer_commission'=>bcsub($mer_money['mer_commission'],$commission,2)]);
            if (empty($res)) {
                exception('提现失败');
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        return $param;
    }

    /**
     * 根据推广员查询商家信息
     * @Author: 易军辉
     * @DateTime:2024-07-22 16:31
     * @param $where
     * @param $page
     * @param $limit
     * @param $order
     * @param $field
     */
    public static function getListByPromotion($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        /***************************组装条件***********************************************/
        $where_sql = "";
        foreach ($where as $key=>$val){
            if($where_sql!=""){
                $where_sql .=" and ";
            }
            if(is_array($val[2])) {
                $where_sql .= "a." . $val[0] . " " . $val[1] . "(" . implode(',', $val[2]) . ")";
            }if($val[1] == 'is'){
                $where_sql .="a.".$val[0]." ".$val[1]." ".$val[2];
            }else{
                $where_sql .="a.".$val[0]." ".$val[1]." '".$val[2]."' ";
            }
        }
        $sql = <<<SQL
                SELECT 
                a.id,
                a.mer_account,
                a.create_time,
                a.remark,
                SUM(CASE WHEN o.status IN (3, 4, 5, 6) THEN 1 ELSE 0 END) AS open_num,
                SUM(CASE WHEN o.status = 7 THEN 1 ELSE 0 END) AS success_num
                from ya_merchant as a
                LEFT JOIN ya_shop_order as o on o.merchant_id =a.id
                where {$where_sql}
                GROUP BY a.id
                ORDER BY a.create_time desc
            SQL;
        if ($page == 0 || $limit == 0) {
            return Db::query($sql);
        }
        $count =  Db::query("select count(*) as count from (".$sql.") as co");
        $count=$count[0]['count'];
        $pages = ceil($count / $limit);
        // 计算偏移量
        $offset = ($page - 1) * $limit;
        $list = Db::query($sql. " LIMIT $offset, $limit");
        return compact('count', 'pages', 'page', 'limit', 'list');
    }

    /**
     * 重置密码
     * @Author: 易军辉
     * @DateTime:2024-10-13 17:43
     * @param $ids 商家ID
     * @param $param 密码
     * @return array
     * @throws \think\Exception
     */
    public static function repwd($ids,$param)
    {
        $model = new MerchantModel();
        $pk = $model->getPk();
        $list = $model->where($pk, 'in', $ids)->field('id')->select()->toArray();
        $mer_user_ids = [];
        foreach ($list as $key=>$val){
            $mer_user_id = Db::name('merchant_user')
                ->where('is_admin',1)
                ->where('mer_id',$val['id'])
                ->order('mer_user_id asc')
                ->value('mer_user_id');
            if($mer_user_id){
                $mer_user_ids[] = $mer_user_id;
            }
        }
        if(count($mer_user_ids)<=0){
            exception("系统繁忙，请稍后再试");
        }
        // 启动事务
        $model->startTrans();
        try {
            $res = Db::name('merchant_user')
                ->where('is_admin',1)
                ->whereIn('mer_user_id',$mer_user_ids)
                ->update([
                    'password'=>password_hash($param['password'], PASSWORD_BCRYPT),
                    'update_uid'=>user_id(),
                    'update_time'=>date('Y-m-d H:i:s')
                ]);
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        MerchantUserCache::del($mer_user_ids);
        return true;
    }
}
